//
//  Utils.m
//  Locbest
//
//  Created by ximenwuyou on 15-12-14.
//  Copyright (c) 2015年 ximenwuyou. All rights reserved.
//

#import "Utils.h"
#import "AppDelegate.h"
#import <CommonCrypto/CommonDigest.h>
#import "AppGlobalContext.h"
//#import "GTMBase64.h"
#import <AVFoundation/AVFoundation.h>
#import "RealReachability.h"
//#import "AFNetworkReachabilityManager.h"
#import <sys/sysctl.h>
#import "CustomTabBarController.h"

@implementation Utils

+ (UIColor*)colorWithHexString:(NSString*)hex
{
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor grayColor];
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    
    if ([cString length] != 6) return  [UIColor grayColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}


+ (BOOL)isNetworkAvailableShowToast:(BOOL)isShow
{
    BOOL isExistenceNetwork = NO;
//    Reachability *reacha = [Reachability reachabilityWithHostName:@"www.apple.com"];
//    switch ([reacha currentReachabilityStatus])
//    {
//        case NotReachable:
//            isExistenceNetwork = NO;
//            break;
//        case ReachableViaWiFi:
//            isExistenceNetwork = YES;
//            break;
//        case ReachableViaWWAN:
//            isExistenceNetwork = YES;
//            break;
//        default:
//            break;
//    }
//    if (!isExistenceNetwork && isShow)
//    {
//        [Utils showToast:@"请检查网络连接！"];
//    }
    return isExistenceNetwork;
}

/*!
 @method
 @abstract     获取当前时间转换为字符串格式
 @param      format : 格式
 @result       返回当前时间字符串
 */
+ (NSString *)getNowDateTimeWithFormat:(NSString *)format
{
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
    [dateformat setDateFormat:format];
    NSString *str = [dateformat stringFromDate:nowDate];
    return str;
}

/*!
 @method
 @abstract     获取当前时间  NSDate类型
 @param        string : 时间
 @result       返回当前时间NSDate
 */
+ (NSDate *)getNowDateTimeDate:(NSString *)string
{
    NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];
    [dateformater setDateFormat:@"yyyyMMddHHmmsss"];
    NSDate *date_ = [dateformater dateFromString:string];
    return date_;
}

/*!
 @method
 @abstract     比较两个时间之间的时间差，秒为单位
 @param        nowDate : 当前时间
 @param        oldDate : 之前的时间
 @result       返回两个时间之间的间隔秒数
 */
+ (float)getSecondsBetweenTwoDates:(NSDate *)nowDate andOld:(NSDate *)oldDate
{
    NSTimeInterval seconds = [nowDate timeIntervalSinceDate:oldDate];
    return seconds;
}

// 应用版本号
+ (NSString *)getAppVersion
{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

//返回沙盒路径
+ (NSString *)getDocumentDir
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
}

//获取文件完整路径
+ (NSString *)getFilePath:(NSString *)fileName fromDir:(NSString *)dir
{
     return [dir stringByAppendingPathComponent:fileName];
}

//大写
+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (int)strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

//小写
+ (NSString *)md5FromString:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (int)strlen(cStr), result); // This is the md5 call
    return [NSString
            stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3], result[4], result[5],
            result[6], result[7], result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]];
}

//+ (NSString*)encodeBase64String:(NSString * )input {
//    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//    data = [GTMBase64 encodeData:data];
//    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    return base64String;
//}
//
//+ (NSString*)decodeBase64String:(NSString * )input {
//    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//    data = [GTMBase64 decodeData:data];
//    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    return base64String;
//}

/********************** NSDate Utils ***********************/
+ (NSString *)getTimeSp
{
    NSDate *fromdate = [NSDate date];
    NSTimeInterval time = [fromdate timeIntervalSince1970]*1000;
    return [NSString stringWithFormat:@"%.0f",time];
}

+ (NSString *)stringFromDate:(NSDate *)date formatter:(NSString *)formatter {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatter];
    return [dateFormatter stringFromDate:date];
}

+ (NSDate *)dateFromString:(NSString *)dateString
                 formatter:(NSString *)formatter;
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatter];
    return [dateFormatter dateFromString:dateString];
}

+ (NSString *)timeFormatted:(int)totalSeconds
{
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
//    int hours = totalSeconds / 3600;
    return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}

+ (NSString *)convertSecondToTime:(int)totalSeconds
{
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    if (hours > 0)
    {
        return [NSString stringWithFormat:@"%02d:%02d:%02d", hours,minutes, seconds];
    }
    return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}

+ (NSString *)convert10TimespToString:(NSString *)timesp
{
    NSTimeInterval time = [timesp doubleValue] + 28800;//因为时差问题要加8小时 == 28800 sec
    NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-M-d HH:mm:ss"];
    return [dateFormatter stringFromDate: detaildate];
}

#pragma mark - MBPROGRESS
+ (void)showToast:(NSString *)msage withCtrl:(UIViewController *)viewCtrl {
    MBProgressHUD *hud =
    [MBProgressHUD showHUDAddedTo:viewCtrl.view animated:YES];
    
    // Configure for text only and offset down
    hud.mode = MBProgressHUDModeText;
    hud.label.text = msage;
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hideAnimated:YES afterDelay:2.5];
}

+ (void)showToastMessage:(NSString *)msage {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    
    // Configure for text only and offset down
    hud.mode = MBProgressHUDModeText;
    hud.label.text = msage;
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hideAnimated:YES afterDelay:2.0];
}

+ (MBProgressHUD *)showMBHUD:(NSString *)title
                    withCtrl:(UIViewController *)viewCtrl {
    if (viewCtrl.navigationController.view == nil) {
        return nil;
    }else{
        MBProgressHUD *hud =
        [MBProgressHUD showHUDAddedTo:viewCtrl.navigationController.view
                             animated:YES];
        hud.label.text = title;
        // Configure for text only and offset down
        [hud showAnimated:YES];
        return hud;
    }
}
/**
 *  关闭loading条
 */
+ (void)dismissMBHUD:(MBProgressHUD *)mbHud {
    [mbHud hideAnimated:YES];
}

+ (BOOL)phoneNumberCheck:(NSString *)phoneNumber
{
    if (phoneNumber.length != 11)
    {
//        [Utils showToast:@"手机号码格式不正确，请重新填写"];
        return NO;
    }
    
    NSString *phoneRule = @"^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8]))\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRule];
    BOOL isMatch = [pred evaluateWithObject:phoneNumber];
    if (!isMatch)
    {
//        [Utils showToast:@"手机号码格式不正确，请重新填写"];
        return NO;
    }

    return YES;
}


/**
 获取文件大小
 @param localPath 待计算的localPath, 为全路径， 即 /应用/Documents.....
 @return  long
 */
+ (long)getFileSizeInPath:(NSString *)localPath
{
    NSFileManager *mgr = [NSFileManager defaultManager];
    if ([mgr fileExistsAtPath:localPath])
    {
        NSDictionary *attributeDic = [mgr attributesOfItemAtPath:localPath error:nil];
        return (long)attributeDic.fileSize;
    }
    return 0;
}

+ (NSInteger)getCurrentYear
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    return [dateComponent year];
}

+ (BOOL)isStringAllTheSame:(NSString*)str
{
    NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableSet   *set = [[NSMutableSet alloc] init];
    for (int i= 0; i<str.length; i++)
    {
        NSRange ran = NSMakeRange(i, 1);
        [arr addObject:[str substringWithRange:ran]];
    }
    [set addObjectsFromArray:arr];
    if (set.count == 1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+ (BOOL)isIncreaseOrDecreaseInt:(NSString *)str
{
    NSScanner* scan = [NSScanner scannerWithString:str];
    int val ;
    int BiggerOrSmaller = 0;
    BOOL isSimple = YES;
    // [scan scanInt:&val] && [scan isAtEnd] :判断string是否全为数字,如果是返回YES,否则返回NO
    if ([scan scanInt:&val] && [scan isAtEnd])
    {
        for (int i= 0; i<str.length -1 ; i++)
        {
            NSRange ran1 = NSMakeRange(i, 1);
            NSRange ran2 = NSMakeRange(i+1, 1);
            int m = [[str substringWithRange:ran1] intValue];
            int n = [[str substringWithRange:ran2] intValue];
            if (i == 0)
            {
                if (n-m == 1 || n-m== -1)
                {
                    BiggerOrSmaller = n-m;
                }
                else
                {
                    isSimple = NO;
                    break;
                }
            }
            else
            {
                if ( n-m != BiggerOrSmaller)
                {
                    isSimple = NO;
                    break;
                }
            }
        }
        return isSimple;
    }
    else
    {
        return NO;
    }
    
}

+ (BOOL)isStringTooLong:(NSString*)str
{
    CGSize size = [str sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName, nil]];
    CGFloat nameW = size.width;
    BOOL isLong;
    if (nameW > SCREEN_WIDTH*0.55 )
    {
        isLong = YES;
    }
    else
    {
        isLong = NO;
    }
    return isLong;
}

//获得设备型号
+ (NSString *)getCurrentDeviceModel
{
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone5,1"] || [platform isEqualToString:@"iPhone5,2"] || [platform isEqualToString:@"iPhone5,3"] || [platform isEqualToString:@"iPhone5,4"] || [platform isEqualToString:@"iPhone6,1"] || [platform isEqualToString:@"iPhone6,2"])
        return @"iPhone 5";
//    if () return @"iPhone 5 (A1429/A1442)";
//    if () return @"iPhone 5c (A1456/A1532)";
//    if () return @"iPhone 5c (A1507/A1516/A1526/A1529)";
//    if () return @"iPhone 5s (A1453/A1533)";
//    if () return @"iPhone 5s (A1457/A1518/A1528/A1530)";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    return platform;
}
+ (BOOL)checkBankCardNo:(NSString*)cardNo{
    NSString * lastNum = [[cardNo substringFromIndex:(cardNo.length-1)]copy];//取出最后一位
    
    NSString * forwardNum = [[cardNo substringToIndex:(cardNo.length -1)]copy];//前15或18位
    
    NSMutableArray * forwardArr = [[NSMutableArray alloc] initWithCapacity:0];
    
    for (int i=0; i<forwardNum.length; i++) {
        
        NSString * subStr = [forwardNum substringWithRange:NSMakeRange(i,1)];
        
        [forwardArr addObject:subStr];
        
    }
    
    
    
    NSMutableArray * forwardDescArr = [[NSMutableArray alloc] initWithCapacity:0];
    
    for (NSInteger i = forwardArr.count-1; i> -1; i--) {//前15位或者前18位倒序存进数组
        
        [forwardDescArr addObject:forwardArr[i]];
        
    }
    
    NSMutableArray * arrOddNum = [[NSMutableArray alloc] initWithCapacity:0];//奇数位*2的积 < 9
    
    NSMutableArray * arrOddNum2 = [[NSMutableArray alloc] initWithCapacity:0];//奇数位*2的积 > 9
    
    NSMutableArray * arrEvenNum = [[NSMutableArray alloc] initWithCapacity:0];//偶数位数组
    
    for (int i=0; i< forwardDescArr.count; i++) {
        
        int num = [forwardDescArr[i] intValue];
        
        if (i%2) {//偶数位
            
            [arrEvenNum addObject:[NSNumber numberWithInt:num]];
            
        }else{//奇数位
            
            if (num *2 < 9) {
                
                [arrOddNum addObject:[NSNumber numberWithInt:num *2]];
                
            }else{
                
                int decadeNum = (num *2) / 10;
                
                int unitNum = (num *2) % 10;
                
                [arrOddNum2 addObject:[NSNumber numberWithInt:unitNum]];
                
                [arrOddNum2 addObject:[NSNumber numberWithInt:decadeNum]];
                
            }
            
        }
        
    }
    __block  NSInteger sumOddNumTotal = 0;
    
    [arrOddNum enumerateObjectsUsingBlock:^(NSNumber * obj,NSUInteger idx, BOOL *stop) {
        
        sumOddNumTotal += [obj integerValue];
        
    }];
    
    
    
    __block NSInteger sumOddNum2Total = 0;
    
    [arrOddNum2 enumerateObjectsUsingBlock:^(NSNumber * obj,NSUInteger idx, BOOL *stop) {
        
        sumOddNum2Total += [obj integerValue];
        
    }];
    
    
    
    __block NSInteger sumEvenNumTotal =0 ;
    
    [arrEvenNum enumerateObjectsUsingBlock:^(NSNumber * obj,NSUInteger idx, BOOL *stop) {
        
        sumEvenNumTotal += [obj integerValue];
        
    }];
    
    NSInteger lastNumber = [lastNum integerValue];
    
    NSInteger luhmTotal = lastNumber + sumEvenNumTotal + sumOddNum2Total + sumOddNumTotal;
    
    
    
    return (luhmTotal%10 ==0)?YES:NO;
    

}

+(BOOL)checkIdentityCardNo:(NSString*)cardNo{
    if (cardNo.length != 18) {
        return  NO;
    }
    NSArray* codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil];
    NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil]  forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];
    
    NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]];
    
    int val;
    BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
    if (!isNum) {
        return NO;
    }
    int sumValue = 0;
    
    for (int i =0; i<17; i++) {
        sumValue+=[[cardNo substringWithRange:NSMakeRange(i , 1) ] intValue]* [[codeArray objectAtIndex:i] intValue];
    }
    
    NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue%11]];
    
    if ([strlast isEqualToString: [[cardNo substringWithRange:NSMakeRange(17, 1)]uppercaseString]]) {
        return YES;
    }
    return  NO;
}
+ (BOOL)isValidChinese:(NSString *)string{
    NSString *chineseRegex = @"^[\\u4e00-\\u9fa5]+$";
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",chineseRegex];
    return [pre evaluateWithObject:string];
}
+ (BOOL)isValidNumber:(NSString *)string{
    NSString *numberRegex= @"^[0-9]*$";
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",numberRegex];
    return [pre evaluateWithObject:string];
}
+ (BOOL)isEmpty:(NSString *)string{
    if (!string) {
        return YES;
    }else{
        NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
        NSString *str = [string stringByTrimmingCharactersInSet:set];
        if (str.length == 0) {
            return YES;
        }else{
            return NO;
        }
    }
}

//+ (UIView *)showNoDataView:(UIView *)rootView Title:(NSString *)title{
//    
//    CustomNoDataView *noDataView = [[CustomNoDataView alloc] initWithRootView:rootView Title:title];
//    return noDataView;
//    
//}
//
//+ (UIView *)showNoDataViewForHistory:(UIView *)rootView Title:(NSString *)title{
//    
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT * 0.153, CGRectGetWidth(rootView.frame), CGRectGetHeight(rootView.frame) - SCREEN_HEIGHT * 0.153)];
//    view.backgroundColor = PlaceHolderColor;
//    view.userInteractionEnabled = NO;
//    [rootView addSubview:view];
//    
//    UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"NoDataImage"]];
//    imageV.center = view.center;
//    imageV.centerY = view.centerY - SCREEN_HEIGHT * 0.153;
//    [view addSubview:imageV];
//    
//    UILabel *titleLabel = [[UILabel alloc] init];
//    titleLabel.text = title;
//    titleLabel.textAlignment = NSTextAlignmentCenter;
//    titleLabel.font = CustomerFont(DQH_Bold, 20);
//    titleLabel.textColor = [UIColor colorWithRed:124/255.0 green:124/255.0 blue:124/255.0 alpha:1];
//    [view addSubview:titleLabel];
//    
//    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.equalTo(imageV.mas_top).offset(-20);
//        make.height.equalTo(@(20));
//        make.centerX.equalTo(imageV.mas_centerX);
//        make.width.equalTo(view.mas_width);
//    }];
//    
//    return view;
//}
//
//+ (void)hideNoDataView:(UIView *)view{
//    if (view && view.superview) {
//        [view removeFromSuperview];
//    }
//}

+ (UIImage *)createCodeGenerator:(NSString *)urlString{
    
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2. 恢复滤镜的默认属性
    
    [filter setDefaults];
    
    // 3. 将字符串转换成
    
    NSData *data = [urlString dataUsingEncoding:NSUTF8StringEncoding];
    
    // 4. 通过KVO设置滤镜inputMessage数据
    
    [filter setValue:data forKey:@"inputMessage"];
    
    // 5. 获得滤镜输出的图像
    
    CIImage *outputImage = [filter outputImage];
    
    // 6. 将CIImage转换成UIImage，并放大显示
    
    return [UIImage imageWithCIImage:outputImage scale:20.0 orientation:UIImageOrientationUp];
}

+ (UIViewController *)CurrentViewController{
    UIWindow *window = TheAppDelegate.window;
    if ([window.rootViewController isKindOfClass:[CustomTabBarController class]]) {
        CustomTabBarController *tabBar = (CustomTabBarController *)window.rootViewController;
        UINavigationController *nav = (UINavigationController *)tabBar.viewControllers[tabBar.selectedIndex];
        UIViewController *vc = nav.visibleViewController;
        return vc;
    }
    return nil;
}

+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)ciImage size:(CGFloat)widthAndHeight
{
    CGRect extentRect = CGRectIntegral(ciImage.extent);
    CGFloat scale = MIN(widthAndHeight / CGRectGetWidth(extentRect), widthAndHeight / CGRectGetHeight(extentRect));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extentRect) * scale;
    size_t height = CGRectGetHeight(extentRect) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CGColorSpaceRelease(cs);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:ciImage fromRect:extentRect];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extentRect, bitmapImage);
    
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    
    //return [UIImage imageWithCGImage:scaledImage]; // 黑白图片
    UIImage *newImage = [UIImage imageWithCGImage:scaledImage];
    CGImageRelease(scaledImage);
    return newImage;
}

void ProviderReleaseData (void *info, const void *data, size_t size){
    free((void*)data);
}
+ (UIImage*)imageBlackToTransparent:(UIImage*)image withRed:(CGFloat)red andGreen:(CGFloat)green andBlue:(CGFloat)blue{
    const int imageWidth = image.size.width;
    const int imageHeight = image.size.height;
    size_t      bytesPerRow = imageWidth * 4;
    uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
    // 遍历像素
    int pixelNum = imageWidth * imageHeight;
    uint32_t* pCurPtr = rgbImageBuf;
    for (int i = 0; i < pixelNum; i++, pCurPtr++){
        if ((*pCurPtr & 0xFFFFFF00) < 0x99999900)    // 将白色变成透明
        {
            // 改成下面的代码，会将图片转成想要的颜色
            uint8_t* ptr = (uint8_t*)pCurPtr;
            ptr[3] = red; //0~255
            ptr[2] = green;
            ptr[1] = blue;
        }
        else
        {
            uint8_t* ptr = (uint8_t*)pCurPtr;
            ptr[0] = 0;
        }
    }
    // 输出图片
    CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
    CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,
                                        kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider,
                                        NULL, true, kCGRenderingIntentDefault);
    CGDataProviderRelease(dataProvider);
    UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
    // 清理空间
    CGImageRelease(imageRef);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return resultUIImage;
}

+ (UIImage *)generatesHighDefinitionColorCode:(NSString *)urlString andSize:(CGFloat)widthAndHeight withRGB:(NSDictionary *)rgbColor{
    
    UIImage *imgCode = [Utils createCodeGenerator:urlString];
    imgCode = [Utils createNonInterpolatedUIImageFormCIImage:imgCode.CIImage size:widthAndHeight];
    
    imgCode = [Utils imageBlackToTransparent:imgCode withRed:[rgbColor[@"red"] floatValue] andGreen:[rgbColor[@"green"] floatValue] andBlue:[rgbColor[@"blue"] floatValue]];
    
    return imgCode;
}

+ (UIImage *)generatesHighDefinitionColorCode:(NSString *)urlString andSize:(CGFloat)widthAndHeight withRed:(CGFloat)red andGreen:(CGFloat)green andBlue:(CGFloat)blue{

    UIImage *imgCode = [Utils createCodeGenerator:urlString];
    imgCode = [Utils createNonInterpolatedUIImageFormCIImage:imgCode.CIImage size:widthAndHeight];
    imgCode = [Utils imageBlackToTransparent:imgCode withRed:red andGreen:green andBlue:blue];
    
    return imgCode;
}

+ (NSString *)returnSafeTelPhoneTextStringWithStandTelPhoneTextString:(NSString *)standPhone{
 
    NSString *temp = @"";
    if (standPhone && standPhone.length == 11) {
        temp = [NSString stringWithFormat:@"%@****%@",[standPhone substringToIndex:3],[standPhone substringWithRange:NSMakeRange(7, 4)]];
    }
    return temp;
}

+ (UIView  * _Nullable)showNoDataView:(UIView * _Nonnull)rootView Title:(NSString * _Nullable)title {
    return [UIView new];
}

+ (void)hideNoDataView:(UIView * _Nonnull)view {
    
}

+ (BOOL)validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
    
}

+ (NSDictionary *)readLocalDataWithFileName:(NSString *)fileName fileType:(NSString *)fileType{
    NSData *jsonData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:fileType]];
    if (jsonData) {
        if ([[jsonData objectFromJSONData] isKindOfClass:[NSDictionary class]]) {
           NSDictionary *dataDic =  [jsonData objectFromJSONData];
            return dataDic;
        }
    }
    return nil;
}


@end
